package meta

import (
	"data-system/config"
	"data-system/models"
	"data-system/tools"

	"github.com/gogf/gf/v2/util/gconv"
	"github.com/samber/lo"
)

var NodeTypes = make([]string, 0)
var SerialMetaPool = make(map[string]*models.SerialMeta)

func Load() {
	loadSerialMeta()
	loadPageLogicMeta()
}

func loadSerialMeta() {
	serialMetaContents, _ := tools.ReadJsonDir(config.Cfg().SerialMetaDir)
	for _, content := range serialMetaContents {
		var serialMeta models.SerialMeta
		if err := gconv.Structs(content, &serialMeta); err != nil {
			continue
		}
		serialMeta.Columns = lo.Map(serialMeta.Columns, func(column models.SerialMetaColumn, _ int) models.SerialMetaColumn {
			column.NodeType = serialMeta.NodeType
			return column
		})
		serialMeta.DataLine = len(serialMeta.TbHeaders)
		NodeTypes = append(NodeTypes, serialMeta.NodeType)
		SerialMetaPool[serialMeta.NodeType] = &serialMeta
	}
}

func GetSerialMeta(nodeType string) *models.SerialMeta {
	return SerialMetaPool[nodeType]
}

func GetNodeTypes() []string {
	return NodeTypes
}

var PageLogicMetaPool = make(map[string]*models.PageLogicMeta)

func loadPageLogicMeta() {
	pageLogicMetaContents, _ := tools.ReadJsonDir(config.Cfg().SerialMetaDir)
	for _, content := range pageLogicMetaContents {
		var pageLogicMeta models.PageLogicMeta
		if err := gconv.Structs(content, &pageLogicMeta); err != nil {
			continue
		}
		PageLogicMetaPool[pageLogicMeta.Key] = &pageLogicMeta
	}
}

func GetPageLogicMeta(key string) *models.PageLogicMeta {
	return PageLogicMetaPool[key]
}
